/*User program on Nachos
  For project 4
*/

/*Author: Yuzhe Wu 4/14*/

#include "create.h"

int moneycalculate(struct examSheet* Sheet) {/* Calculate the total amount of the bill, Formular: money = basic($10) + shotmoney($50) + imageNum * moneyPerImage($30)*/
	int money = BASIC;   
	if(Sheet->needShot==true){
		money+=SHOTMONEY;
	}
	if(Sheet->needXray==true){
		money+=(Sheet->imageNum)*IMAGEMONEY;
	}
	return money;
}

void main() {

	bool debugFlag = true;
	int cashierRoomCounterValue = 0;
	struct examSheet myLocalExamSheet;

	Printf("P4DEBUG: I am cashier, in!\n");
	doCreate();
	if(debugFlag == true) {
		Printf("myDEBUG: Cashier : I entered!\n");
	}
	
	while(1){
		rpcAcquireLock(cashierRoomLock); /*The similar scenario as what happened in the waiting room*/ 
		
		
		if((cashierRoomCounterValue = rpcGetValueMV(cashierRoomCounter,0))>0) {
			rpcSignalCV(cashierRoomLock, patientWaitingCRCV);		
			rpcSetValueMV(cashierRoomCounter,0,cashierRoomCounterValue-1);
			rpcSetValueMV(cashierState,0,BUSY);
			if(debugFlag == true) {
				Printf("myDEBUG:cashier is BUSY now\n");
			}
		}

		else{
			rpcSetValueMV(cashierState,0,FREE); /*nobody is waiting in line*/ 
			if(debugFlag == true) {
				Printf("myDEBUG:Cashier is FREE now\n");
			}
		}

		rpcAcquireLock(cashierLock);
		rpcReleaseLock(cashierRoomLock);
		rpcWaitCV(cashierLock,cashierPatientCV); /*wait for patient to come*/

		rpcGetExamSheet(cashierExamSheet, &myLocalExamSheet);
		Printf("Cashier receives the examination sheet from Adult Patient [%d]\n",myLocalExamSheet.patientID);
		
		rpcSetValueMV(bill,0,moneycalculate(&myLocalExamSheet));
		Printf("Cashier reads the examination sheet of Adult Patient [%d] and asks him to pay $[%d].\n",myLocalExamSheet.patientID, rpcGetValueMV(bill,0));

		rpcSignalCV(cashierLock, cashierPatientCV);  /*Give the bill to the patient. Wait for money given*/
		rpcWaitCV(cashierLock,cashierPatientCV); 
		/*Waiting for patient to pay money*/
		
		rpcGetExamSheet(cashierExamSheet, &myLocalExamSheet);
		Printf("Cashier accepts $[%d] from Adult Patient [%d].\n",rpcGetValueMV(bill,0),myLocalExamSheet.patientID);
		/*print for parent*/
		
		/*Give the receipt to the patient*/
		Printf("Cashier gives a receipt of $[%d] to Adult Patient [%d].\n",rpcGetValueMV(bill,0),myLocalExamSheet.patientID);
		/*print for parent*/
		
		rpcSignalCV(cashierLock, cashierPatientCV);
		rpcWaitCV(cashierLock,cashierPatientCV);
		rpcReleaseLock(cashierLock);
		
	/*rpcAcquireLock(patientLeftNumLock);
		
		if(rpcGetValueMV(patientLeftNum,0) == rpcGetValueMV(patientNum,0)) {
			Exit(0);
		}
		rpcReleaseLock(patientLeftNumLock);
	*/
	}

}